package com.bw.controller;

import com.alibaba.excel.EasyExcel;
import com.bw.entity.Bing;
import com.bw.entity.Dict;
import com.bw.entity.Zxt;
import com.bw.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class TuController {

    @Autowired
    BookService bookService;

    @RequestMapping("/tu.do")
    public String tu(Model model){
        // 渲染下拉框
       List<Dict> typeList = bookService.selectBookType();
       // 给页面传值
        model.addAttribute("typeList",typeList);
        return "tu"; // 返回HTML 页面
    }


    @RequestMapping("zxt.do")
    @ResponseBody // 返回JSON格式的数据
    public List<Zxt> zxt(Integer typeId){

        return bookService.zxt(typeId);

    }
    @RequestMapping("bing.do")
    @ResponseBody // 返回JSON格式的数据
    public List<Bing> bing(Integer typeId){

        return bookService.bing(typeId);

    }
    @RequestMapping("excel.do")

    public void excel(Integer typeId, HttpServletResponse response) throws Exception {

        List<Bing> bing = bookService.bing(typeId);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("书籍导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Bing.class).sheet("sheet页").doWrite(bing);

    }
}
